package uimain;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import JsonModel.Group;
import JsonModel.User;
import Net.JsonParse;
import Utilities.Configuration;
import adapter.AdapterAllGroup;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.actionbarsherlock.app.SherlockFragment;
import com.adgroup.smartnote.CreateGroupActivity;
import com.adgroup.smartnote.DetailGroupActivity;
import com.adgroup.smartnote.R;
import com.adgroup.smartnote.SmartNoteActivity;

import database.Database;

public class PrivateNotes extends SherlockFragment{

	ListView lv;
	ProgressBar progressWaiting;
	LinearLayout rootLogin;
	Button btnLogin;
	TextView tvEmpty;
	User u;
	AdapterAllGroup.Adapter adapAllGroup;
	ArrayList<Group> groups;
	int page;
	private View v;
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View viewPrivateNote = inflater.inflate(R.layout.private_notes, container, false);
		return viewPrivateNote;
	}
	@SuppressWarnings("static-access")
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
		
		lv = (ListView) getView().findViewById(R.id.listViewPrivateNote);
		progressWaiting = (ProgressBar) getView().findViewById(R.id.progressBarWaitingPrivateNote);
		rootLogin = (LinearLayout) getView().findViewById(R.id.rootLoginPrivateNote);
		btnLogin = (Button) getView().findViewById(R.id.buttonLoginPrivateNote);
		tvEmpty = (TextView) getView().findViewById(R.id.textViewEmptyPrivateNote);
		
		///add footer iv
		v = PrivateNotes.this.getSherlockActivity().getLayoutInflater().from(PrivateNotes.this.getSherlockActivity()).inflate(R.layout.footerwating, null);
		lv.addFooterView(v);
		v.setVisibility(View.GONE);
		lv.setOnScrollListener(new EndlessScrollListener());
		//set adapter for listview
		groups = new ArrayList<Group>();
		page = 1;
		adapAllGroup = new AdapterAllGroup(PrivateNotes.this, groups).new Adapter();
		lv.setAdapter(adapAllGroup);
		rootLogin.setVisibility(View.GONE);
		tvEmpty.setVisibility(View.GONE);
		progressWaiting.setVisibility(View.GONE);
		
		u = new Database(PrivateNotes.this.getSherlockActivity()).getUser();
		if(u==null){
			rootLogin.setVisibility(View.VISIBLE);
		}
		else{
			new AsyncGetAllGroup().equals(new String[]{u.getUserId()});
		}
		//login
		btnLogin.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				
			}
		});
	}
	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		u = new Database(PrivateNotes.this.getSherlockActivity()).getUser();
		if(u!=null){
			if(rootLogin.getVisibility()==View.VISIBLE){
				rootLogin.setVisibility(View.GONE);
				new AsyncGetAllGroup().equals(new String[]{u.getUserId()});
			}
		}
	}
	@SuppressWarnings("static-access")
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if(requestCode==Configuration.requestPrivateNoteLogin && resultCode==PrivateNotes.this.getSherlockActivity().RESULT_OK){//register then login			
			
		}
	}
	
	//class load more search friend
	public class EndlessScrollListener implements OnScrollListener {

		private int visibleThreshold;
		private int previousTotal;
		private boolean loading;

		public EndlessScrollListener() {
			visibleThreshold = 1;
			previousTotal = 0;
			loading = true;
		}

		public void onScroll(AbsListView view, int firstVisibleItem,
				int visibleItemCount, int totalItemCount) {
			if (loading) {
				if (totalItemCount > previousTotal) {
					loading = false;
					previousTotal = totalItemCount;			
				}
			}
			if (!loading
					&& (totalItemCount - visibleItemCount) <= (firstVisibleItem + visibleThreshold)) {
				if(u!=null){
					new AsyncGetAllGroup().execute(new String[]{u.getUserId()});
				}
				loading = true;
				Log.d("log","load more");
			}			
		}

		public void onScrollStateChanged(AbsListView view, int scrollState) {
			// TODO Auto-generated method stub

		}

	}
	//class load all group
	class AsyncGetAllGroup extends AsyncTask<String, Void, String>
	{
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			if(page==1){
				progressWaiting.setVisibility(View.VISIBLE);
			}
			else{
				v.setVisibility(View.VISIBLE);
			}
		}
		@Override
		protected String doInBackground(String... params) {
			return new JsonParse().getAllGroup(PrivateNotes.this.getSherlockActivity(), params[0], page++);
		}
		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			try {
				JSONObject json = new JSONObject(result);
				String r = json.getString(Configuration.result);
				if(!r.equalsIgnoreCase(Configuration.norow)){
					JSONArray arr = json.getJSONArray(Configuration.result);
					for(int i=0;i<arr.length();i++){
						JSONObject obj = arr.getJSONObject(i);
						String groupId = obj.getString(Group.keyGroupId);
						String groupCatName = obj.getString(Group.keyGroupCatName);
						String groupCatId = obj.getString(Group.keyGroupCatId);
						String time = obj.getString(Group.keyTime);
						String total = obj.getString(Group.keyTotal);
						String title = obj.getString(Group.keyTitle);
						String numNews = obj.getString(Group.keyNews);
						String groupUserId = obj.getString(Group.keyGroupUserId);
						String link = obj.getString(Group.keylink);
						Group g = new Group(groupId, groupUserId, groupCatId, groupCatName, title, total, time, link, numNews);
						groups.add(g);
					}
					adapAllGroup.setArrayGroup(groups);
					adapAllGroup.notifyDataSetChanged();
				}
				else{
					if(page==2){
						lv.setVisibility(View.GONE);
						lv.setEnabled(false);
						tvEmpty.setVisibility(View.VISIBLE);
					}
				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			progressWaiting.setVisibility(View.GONE);
			v.setVisibility(View.GONE);
			
		}
		
	}
	public void setOnClickItemListView(Group group) {
		Database d = new Database(PrivateNotes.this.getSherlockActivity());
		d.resetGroup();
		d.setGroup(group);
		Intent i = new Intent(PrivateNotes.this.getSherlockActivity(), DetailGroupActivity.class);
		startActivityForResult(i, Configuration.requestDetailGroup);
	}
	
}
